package com.iatinspur;

import com.iatinspur.pojo.MyPeople;

import java.io.*;
/**
 * loadClass     内部加载
 * findClass     根据路径找文件
 * defineClass   主要是加载虚拟机内存
 * resolveClass  主要是连接
 */
public class MyClassLoader extends ClassLoader {
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (name.startsWith("java.lang")) {
            return super.loadClass(name);
        }

        if (name.startsWith("java.io")) {
            return super.loadClass(name);
        }
        InputStream in = null;
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        try {
            in = new FileInputStream(new File("D:\\myClass\\MyPeople.class"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        byte[] buf = new byte[1024];
        int temp;
        try {
            while((temp=in.read(buf))!=-1){
                bo.write(buf, 0, temp);
            }
        }catch (IOException e){

        }
        System.out.println(bo.toByteArray().length);
        return defineClass(name,bo.toByteArray(), 0, bo.toByteArray().length);
    }





    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        MyClassLoader classLoader = new MyClassLoader();
        Class<?> aClass = classLoader.loadClass("com.iatinspur.pojo.MyPeople");
        System.out.println(aClass);

        MyPeople people = new MyPeople();
        System.out.println(people.sayHello());


      //  MyPeople o = (MyPeople)aClass.newInstance();

        // System.err.println(people.sayHello());


    }

}
